class Calculator {
    constructor() {
        this.expressionDisplay = document.getElementById('expression');
        this.resultDisplay = document.getElementById('result');
        this.errorToast = document.getElementById('error-toast');
        this.errorMessage = document.getElementById('error-message');
        
        this.currentExpression = '0';
        this.lastResult = null;
        this.justCalculated = false;
        
        this.init();
    }
    
    init() {
        // 更新时间显示
        this.updateTime();
        setInterval(() => this.updateTime(), 60000);
        
        // 添加键盘监听
        document.addEventListener('keydown', (e) => this.handleKeyboard(e));
        
        // 初始化显示
        this.updateDisplay();
    }
    
    updateTime() {
        const now = new Date();
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        document.querySelector('.status-bar-time').textContent = `${hours}:${minutes}`;
    }
    
    updateDisplay() {
        this.expressionDisplay.textContent = this.currentExpression;
        if (this.lastResult !== null && !this.justCalculated) {
            this.resultDisplay.textContent = this.lastResult;
        } else {
            this.resultDisplay.textContent = '';
        }
    }
    
    appendToExpression(value) {
        if (this.justCalculated && !isNaN(value)) {
            // 如果刚计算完且输入数字，开始新计算
            this.currentExpression = value;
            this.justCalculated = false;
            this.lastResult = null;
        } else if (this.justCalculated && isNaN(value)) {
            // 如果刚计算完且输入运算符，继续使用结果
            this.currentExpression = this.lastResult + value;
            this.justCalculated = false;
        } else {
            // 正常输入
            if (this.currentExpression === '0' && !isNaN(value)) {
                this.currentExpression = value;
            } else {
                this.currentExpression += value;
            }
        }
        
        this.updateDisplay();
    }
    
    clearAll() {
        this.currentExpression = '0';
        this.lastResult = null;
        this.justCalculated = false;
        this.updateDisplay();
    }
    
    clearEntry() {
        // 清除当前输入的数字或运算符
        const lastChar = this.currentExpression.slice(-1);
        if (this.currentExpression.length === 1) {
            this.currentExpression = '0';
        } else {
            this.currentExpression = this.currentExpression.slice(0, -1);
        }
        this.updateDisplay();
    }
    
    deleteLast() {
        if (this.currentExpression.length === 1) {
            this.currentExpression = '0';
        } else {
            this.currentExpression = this.currentExpression.slice(0, -1);
        }
        this.updateDisplay();
    }
    
    async calculate() {
        if (this.currentExpression === '0' || this.currentExpression === '') {
            return;
        }
        
        try {
            const response = await fetch('/calculator/calculate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    expression: this.currentExpression
                })
            });
            
            const data = await response.json();
            
            if (data.success) {
                this.lastResult = data.result;
                this.resultDisplay.textContent = data.result;
                this.justCalculated = true;
            } else {
                this.showError(data.error);
            }
        } catch (error) {
            this.showError('网络错误，请重试');
            console.error('计算错误:', error);
        }
    }
    
    showError(message) {
        this.errorMessage.textContent = message;
        this.errorToast.classList.remove('hidden');
        
        // 3秒后自动隐藏
        setTimeout(() => {
            this.errorToast.classList.add('hidden');
        }, 3000);
    }
    
    handleKeyboard(event) {
        const key = event.key;
        
        // 防止默认行为
        if (['Enter', 'Escape', 'Backspace'].includes(key)) {
            event.preventDefault();
        }
        
        if (key >= '0' && key <= '9') {
            this.appendToExpression(key);
        } else if (key === '.') {
            this.appendToExpression('.');
        } else if (key === '+') {
            this.appendToExpression('+');
        } else if (key === '-') {
            this.appendToExpression('-');
        } else if (key === '*') {
            this.appendToExpression('*');
        } else if (key === '/') {
            this.appendToExpression('/');
        } else if (key === '(' || key === ')') {
            this.appendToExpression(key);
        } else if (key === 'Enter' || key === '=') {
            this.calculate();
        } else if (key === 'Escape') {
            this.clearAll();
        } else if (key === 'Backspace') {
            this.deleteLast();
        }
    }
}

// 全局函数供HTML调用
let calc;

document.addEventListener('DOMContentLoaded', () => {
    calc = new Calculator();
});

function appendToExpression(value) {
    calc.appendToExpression(value);
}

function clearAll() {
    calc.clearAll();
}

function clearEntry() {
    calc.clearEntry();
}

function deleteLast() {
    calc.deleteLast();
}

function calculate() {
    calc.calculate();
} 